package com.fly.core.ds;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutionException;

import com.mysql.cj.jdbc.MysqlDataSource;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 数据源(Mysql直连)管理工具, 方便与连接池连接比较
 * 
 * @author 00fly
 * @version [版本号, 2018-09-26]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
public class NoPool extends BaseDataSource
{
    private static MysqlDataSource dataSource = new MysqlDataSource();
    
    /**
     * <默认构造函数>
     */
    private NoPool()
    {
        super();
    }
    
    // 静态初始化 DataSource
    static
    {
        ResourceBundle config = ResourceBundle.getBundle("jdbc");
        dataSource.setUrl(config.getString("jdbc.url"));
        dataSource.setUser(config.getString("jdbc.username"));
        dataSource.setPassword(config.getString("jdbc.password"));
    }
    
    private static final NoPool SINGLE = new NoPool();
    
    /**
     * 单例获取对象
     * 
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static NoPool getInstance()
    {
        return SINGLE;
    }
    
    /**
     * 获取数据库连接
     * 
     * @return
     * @throws SQLException
     * @throws ExecutionException
     * @throws InterruptedException
     * @see [类、类#方法、类#成员]
     */
    @Override
    public Connection getConnection()
        throws SQLException
    {
        Connection connection = threadLocal.get();
        if (connection == null)
        {
            // 把 connection绑定到当前线程上
            connection = dataSource.getConnection();
            threadLocal.set(connection);
        }
        log.info("★★★★申请资源: {}", connection);
        return connection;
    }
}